package com.comecrd.service.impl;

import com.comecrd.model.User;
import com.comecrd.model.dto.UserDTO;
import com.comecrd.repository.UserMapper;
import com.comecrd.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    
    @Autowired
    private UserMapper userMapper;
    
    @Override
    public User findByOpenId(String openId) {
        return userMapper.selectByOpenId(openId);
    }
    
    @Override
    public boolean existsByOpenId(String openId) {
        Integer count = userMapper.countByOpenId(openId);
        return count != null && count > 0;
    }
    
    @Override
    public User saveOrUpdate(User user) {
        if (user.getId() != null) {
            userMapper.update(user);
        } else {
            // 如果是新用户，检查是否存在相同的openId
            User existingUser = userMapper.selectByOpenId(user.getOpenId());
            if (existingUser != null) {
                user.setId(existingUser.getId());
                userMapper.update(user);
                return user;
            }
            userMapper.insert(user);
        }
        return user;
    }
    
    @Override
    public User findById(Long id) {
        return userMapper.selectById(id);
    }
    
    @Override
    public UserDTO convertToDTO(User user) {
        if (user == null) {
            return null;
        }
        UserDTO userDTO = new UserDTO();
        userDTO.setId(user.getId());
        userDTO.setOpenId(user.getOpenId());
        userDTO.setNickname(user.getNickname());
        userDTO.setAvatarUrl(user.getAvatarUrl());
        userDTO.setGender(user.getGender());
        // User实体中可能没有city字段，暂时注释
        // userDTO.setCity(user.getCity());
        userDTO.setCreatedAt(user.getCreatedAt());
        userDTO.setUpdatedAt(user.getUpdatedAt());
        return userDTO;
    }
}